package service

import (
	"encoding/json"
	"fmt"
	"git.inedcn.com/ined/cmn"
	"math/rand"
	constant "rongyy/src/constants"
	"rongyy/src/helper"
	"rongyy/src/middlewares"
	"rongyy/src/models"
	"strconv"
	"strings"
	"time"
)

type PaymentService struct {
}

func (pc *PaymentService) Pay(req *models.PaymentReq) (*models.PaymentRespData, error) {
	url := cmn.GetEnv("PAYMENT_URL")
	middlewares.Logger.Println(req)
	resp, err := helper.PostJson(url+"/pay", req)
	middlewares.Logger.Println(string(resp))
	pr := &models.PaymentResp{}
	err = json.Unmarshal([]byte(resp), pr)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp failed ", err)
		return nil, err
	}
	ptm := &models.PaymentTrackModel{
		JsonInput:  *req,
		ErrorMsg:   "",
		JsonOutput: string(resp),
	}
	ptm.Create()
	middlewares.Logger.Println(pr)
	data := pr.Data
	prd := &models.PaymentRespData{}
	err = json.Unmarshal([]byte(data), prd)
	// 主动查询
	queryTimes := 0
	var queryTimer *time.Timer
	go func() {
		for {
			switch queryTimes {
			case 0:
				queryTimer = time.NewTimer(40 * time.Second)
			case 1:
				queryTimer = time.NewTimer(60 * time.Second)
			case 2:
				queryTimer = time.NewTimer(80 * time.Second)
			case 3:
				queryTimer = time.NewTimer(100 * time.Second)
			default:
				return
			}
			<-queryTimer.C
			queryTimes++
			middlewares.Logger.Println("主动查询次数: - ", queryTimes)
			// 挂号订单主动查询
			if strings.Contains(req.OrderSn, "R") {
				// 查询订单是否成功
				order, has, err := (&models.PaymentOrders{}).FindByOrder(req.OrderSn)
				if !has {

				}
				if has && order.OrderStatus == 1 {
					// 订单支付成功，直接去确认
					rm := &models.RegisterModel{}
					reg, has, err := rm.FindByOrderSn(req.OrderSn)
					middlewares.Logger.Println("主动查询支付订单信息: - ", reg)
					if has && err == nil {
						if reg.Status == "confirm" && reg.PayStatus == "paid" {
							return
						} else if reg.Status == "locked" && reg.PayStatus == "paying" && reg.AppOrderCode == "" {
							reqReg := &models.Req1101Params{
								TransactionId:    reg.TransactionId,
								ScheduleItemCode: reg.ScheduleItemCode,
								PatientID:        reg.PatientId,
								PayModeCode:      constant.PayModeCode,
								PayFee:           strconv.FormatFloat(req.TotalFee, 'f', -1, 64),
								QueueNo:          "",
								PayAmt:           strconv.FormatFloat(req.TotalFee, 'f', -1, 64),
								PlatformNo:       req.OrderSn,
								OutPayNo:         "",
								PayChannel:       "",
								POSPayStr:        "",
								PayDate:          order.TranDate[0:10],
								PayTime:          order.TranDate[11:],
								UpdateBy:         "active",
							}
							_, err = (&RegistrationService{}).Register(reqReg)
						} else if reg.Status == "locked" && reg.PayStatus == "paying" && reg.AppOrderCode != "" {
							reqRegApp := &models.Req1101Params{
								TransactionId: reg.TransactionId,
								PatientID:     reg.PatientId,
								PayModeCode:   constant.PayModeCode,
								PayFee:        strconv.FormatFloat(req.TotalFee, 'f', -1, 64),
								QueueNo:       "",
								PayAmt:        strconv.FormatFloat(req.TotalFee, 'f', -1, 64),
								PlatformNo:    req.OrderSn,
								OutPayNo:      reg.AppOrderCode,
								PayChannel:    "",
								POSPayStr:     "",
								PayDate:       order.TranDate[0:10],
								PayTime:       order.TranDate[11:],
								UpdateBy:      "scanner",
								AppOrderCode:  reg.AppOrderCode,
							}
							_, err = (&RegistrationService{}).RegisterZJ(reqRegApp)
						}
					}
				}
				middlewares.Logger.Println("GetWxPayInfo GetInConfirmReg", err)
			}
			// 门诊
			if strings.Contains(req.OrderSn, "P") {
				// 查询订单是否成功
				order, has, err := (&models.PaymentOrders{}).FindByOrder(req.OrderSn)
				if !has {

				}
				if has && order.OrderStatus == 1 {
					// 订单支付成功，直接去确认
					pm := &models.PrescriptionModel{}
					ppm, has, err := pm.FindByOrderSn(req.OrderSn)
					middlewares.Logger.Println("主动查询支付订单信息: - ", ppm)
					if has && err == nil {
						if ppm.Status == "confirm" && ppm.PayStatus == "paid" {
							return
						} else if ppm.Status == "prepay" && ppm.PayStatus == "paying" {
							reqOp := &models.Req4906Params{
								PatientId:    ppm.PatientId,
								CardNo:       "",
								OrderNo:      ppm.OrderNo,
								InvoiceNoStr: ppm.InvoiceNo,
								PayAmt:       order.PaymentMoney,
								PlatformNo:   req.OrderSn,
								OutPayNo:     ppm.OrderNo,
								PayDate:      order.TranDate[0:10],
								PayTime:      order.TranDate[11:],
								UpdatedBy:    "active",
								OrderSn:      req.OrderSn,
							}
							_, err = (&OutPatientService{}).CompleteCharge(reqOp)
						}
					}
				}
				middlewares.Logger.Println("GetWxPayInfo GetInConfirmReg", err)
			}
			// 门诊
			if strings.Contains(req.OrderSn, "C") {
				// 查询订单是否成功
				order, has, err := (&models.PaymentOrders{}).FindByOrder(req.OrderSn)
				if !has {

				}
				if has && order.OrderStatus == 1 {
					// 订单支付成功，直接去确认
					// 通知内网订单
				}
				middlewares.Logger.Println("病案快递", err)
			}
		}
	}()
	return prd, nil
}

func (pc *PaymentService) Refund(req *models.RefundReq) (*models.RefundResp, error) {
	url := cmn.GetEnv("PAYMENT_URL")
	resp, err := helper.PostJson(url+"/refund", req)
	pr := &models.RefundResp{}
	err = json.Unmarshal([]byte(resp), pr)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp failed ", err)
		return nil, err
	}
	return pr, nil
}

func (pc *PaymentService) Query(req *models.PaymentReq) (*models.QueryPaymentResp, error) {
	url := cmn.GetEnv("PAYMENT_URL")
	resp, err := helper.PostJson(url+"/query-pay?id=7&order="+req.OrderSn, nil)
	pr := &models.QueryPaymentResp{}
	middlewares.Logger.Println(string(resp))
	err = json.Unmarshal(resp, pr)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp failed ", err)
		return nil, err
	}
	return pr, nil
}

func (pc *PaymentService) QueryByTime(req *models.ReqPaymentQueryByTime) (interface{}, error) {
	//url := cmn.GetEnv("PAYMENT_URL_CCB")
	//resp, err := helper.PostJson(url+"/query-pay-time", req)
	//pr := &models.PaymentQueryByTimeResp{}
	//err = json.Unmarshal(resp, pr)
	//if err != nil {
	//	middlewares.Logger.Println("Unmarshal resp failed ", err)
	//	return nil, err
	//}
	//if len(pr.Data.TxInfo.List) > 0 {
	//	for _, item := range pr.Data.TxInfo.List {
	//		po := &models.PaymentOrders{
	//			OrderSn:      item.Order,
	//			PaymentMoney: item.PaymentMoney,
	//			RefundMoney:  item.RefundMoney,
	//			OrderStatus:  item.OrderStatus,
	//			TranDate:     item.TranDate,
	//		}
	//		has, _ := po.FindByStatus(po.OrderSn, po.OrderStatus)
	//		if !has {
	//			_ = po.Create()
	//		}
	//	}
	//}
	data, err := (&PaymentService{}).QueryCcbTime(req)
	if err != nil {
		fmt.Println("获取银行订单记录错误")
	}
	if data != nil && data.Data.TxInfo.PageCount > 1 {
		i := 0
		for i = 0; i < data.Data.TxInfo.PageCount-1; i++ {
			num, err := strconv.Atoi(req.Page)
			if err != nil {
			}
			req.Page = strconv.Itoa(num + 1)
			(&PaymentService{}).QueryCcbTime(req)
		}
	}
	fmt.Println("获取银行订单记录成功")
	return data, nil
}

func (pc *PaymentService) QueryCcbTime(req *models.ReqPaymentQueryByTime) (*models.PaymentQueryByTimeResp, error) {
	url := cmn.GetEnv("PAYMENT_URL_CCB")
	fmt.Println(req)
	resp, err := helper.PostJson(url+"/query-pay-time", req)

	pr := &models.PaymentQueryByTimeResp{}
	err = json.Unmarshal(resp, pr)
	if err != nil {
		//middlewares.Logger.Println("Unmarshal resp failed ", err)
		return nil, err
	}
	fmt.Println(pr)
	if pr.Data.TxInfo.List == nil {
		return nil, err
	}
	if len(pr.Data.TxInfo.List) > 0 {
		for _, item := range pr.Data.TxInfo.List {
			po := &models.PaymentOrders{
				OrderSn:      item.Order,
				PaymentMoney: item.PaymentMoney,
				RefundMoney:  item.RefundMoney,
				OrderStatus:  item.OrderStatus,
				TranDate:     item.TranDate,
			}
			order, has, _ := po.FindByOrder(po.OrderSn)
			if !has {
				_ = po.Create()
			} else {
				if order.OrderStatus != item.OrderStatus {
					_ = po.UpdateOrderStatus()
				}
			}
		}
	}
	return pr, nil
}

func (pc *PaymentService) PayForPress() (*models.PaymentRespData, error) {
	number := rand.Intn(999999999999999)      // 生成15位以内的随机数
	numberStr := fmt.Sprintf("%015d", number) // 格式化为15位数，不足部分用0填充

	orderSn := "test" + numberStr
	req := &models.PaymentReq{
		MerchantId: constant.MerchantId,
		Desc:       orderSn,
		PayStatus:  "unpaid",
		OutTradeNo: orderSn,
		TotalFee:   0.01,
		ClientIp:   "",
		BusiType:   "reg",
		OrderSn:    orderSn,
		PayWay:     constant.PayWay,
		OpenId:     "oXxoD5cYf_rQDFg9rJyVDbEn4V78",
	}
	url := cmn.GetEnv("PAYMENT_URL")
	//middlewares.Logger.Println(req)
	resp, err := helper.PostJson(url+"/pay", req)
	pr := &models.PaymentResp{}
	err = json.Unmarshal([]byte(resp), pr)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp failed ", err)
		return nil, err
	}
	data := pr.Data
	prd := &models.PaymentRespData{}
	err = json.Unmarshal([]byte(data), prd)
	return prd, nil
}
